import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LXW
 * Date: 2022-04-09
 * Time: 21:17
 */
public class TcpEchoServer {
   private ServerSocket socket = null;
   public TcpEchoServer(int port) throws IOException {
       this.socket = new ServerSocket(port);
   }
   public void start() throws IOException {
       System.out.println("启动服务器");
       while(true) {
           Socket clientSocket = socket.accept();
           processConnection(clientSocket);
       }
   }

    private void processConnection(Socket clientSocket) {
        System.out.println(clientSocket.getInetAddress()+""+clientSocket.getPort()+"客户端建立连接");
        try (InputStream inputStream = clientSocket.getInputStream()){
            try (OutputStream outputStream = clientSocket.getOutputStream()){
                Scanner scanner = new Scanner(inputStream);
                while(!scanner.hasNext()) {
                    System.out.println(clientSocket.getInetAddress()+""+clientSocket.getPort()+"客户端断开连接");
                    break;
                }
                String request = scanner.next();
                String response = process(request);
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();
                System.out.println(clientSocket.getInetAddress()+""+clientSocket.getPort()+
                        "request"+request+"response"+response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String process(String request) {
       return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
